import React from 'react'
import * as ReactDOM from 'react-dom';
import Modal, { ModalProps, ModalFuncProps } from "antd/lib/modal";

let modalInstance: any[] = [];
interface IModalProps extends ModalProps, ModalFuncProps {
	Component: any,
	componentProps: object,
	modalProps: object,
	onOk: (...args: any[]) => void,
	onCancel: () => void,
}

class MyModal extends React.Component<IModalProps>{

	state = { modalVisible: true }
	handleOk = (data: object) => {
		console.log("modalBox-handleOk", data)
		this.props.onOk(data);
	}
	handleCancel = () => {
		console.log("modalBox-handleCancel")
		this.props.onCancel();
	}
	render() {
		let { Component, componentProps, modalProps } = this.props
		return (
			<Modal
				visible={this.state.modalVisible}
				onCancel={this.handleCancel}
				onOk={this.handleOk}
				{...modalProps}>
				<Component {...componentProps}
					onOk={this.handleOk}
					onCancel={this.handleCancel}
				/>
			</Modal>)
	}

}
export default {
	show(Component: any, modalProps = {}, componentProps = {}) {
		// let that = this
		return new Promise((resolve, reject) => {
			let div = document.createElement('div');
			document.body.appendChild(div);
			let onOk = (data: object) => {
				this.hide();
				resolve(data);
			}
			let onCancel = () => {
				this.hide();
				reject();
			}

			ReactDOM.render(<MyModal
				onCancel={onCancel}
				onOk={onOk}
				Component={Component}
				modalProps={modalProps}
				componentProps={componentProps} />, div);
			modalInstance.push(div)
		})

	},
	hide() {
		let div = modalInstance.pop();
		const unmountResult = ReactDOM.unmountComponentAtNode(div);
		if (unmountResult && div.parentNode) {
			div.parentNode.removeChild(div);
		}


	}

}